package cn.innosmart.aq.adapter;

import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.zhy.autolayout.utils.AutoUtils;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import cn.innosmart.aq.R;
import cn.innosmart.aq.application.AQApplication;
import cn.innosmart.aq.bean.AlarmConditionBean;
import cn.innosmart.aq.bean.AquariumBean;
import cn.innosmart.aq.bean.DeviceBean;
import cn.innosmart.aq.camera.models.CameraBean;
import cn.innosmart.aq.camera.protocol.Camera;
import cn.innosmart.aq.util.AppUtil;
import cn.innosmart.aq.util.DeviceConstant;
import cn.innosmart.aq.util.SystemConstant;

/**
 * Created by David on 2015/11/17.
 */
public class FullscreenPTDeviceGridViewAdapter extends BaseAdapter {
    private final int mIconSize;
    private final Typeface tf_fzcy;
    private LayoutInflater mInflater;
    private Context mContext;
    private ArrayList<String> devices = new ArrayList<>();
    private View.OnClickListener onNormalIconClickListener;
    private View.OnClickListener onAlarmIconClickListener;
    private View.OnClickListener onNameClickListener;
    private View.OnClickListener onControlClickListener;
    private Camera.OnStreamInfoUpdate onStreamInfoUpdate = new Camera.OnStreamInfoUpdate() {

        @Override
        public void onFrameRateUpdate(String frameRate) {

        }

        @Override
        public void onFrameResolutionUpdate(String resolution) {

        }

        @Override
        public void onCameraConnected() {

        }


        @Override
        public void onCameraStatus(String did, int status) {
            final CameraBean cameraBean = SystemConstant.cameraBeanHashMap.get(did);
            cameraBean.setStatus(status);
            notifyDataSetChanged();
        }
    };
    private View.OnClickListener onValueClickListener;

    /**
     * @param context
     */
    public FullscreenPTDeviceGridViewAdapter(Context context) {

        tf_fzcy = Typeface.createFromAsset(context.getAssets(), "fonts/fzcy.ttf");

        mInflater = LayoutInflater.from(context);
        mContext = context;
        mIconSize = context.getResources().getDimensionPixelSize(R.dimen.drawer_icon_size);//24dp
        ArrayList<String> allPTDevices = new ArrayList<>();

        if (SystemConstant.aquariumList != null) {
            for (AquariumBean aquariumBean : SystemConstant.aquariumList) {
                System.out.println("AquariumBean:" + aquariumBean.getTitle());

                ArrayList<String> deviceList = aquariumBean.getDeivices();

                for (String address : deviceList) {
                    DeviceBean deviceBean = SystemConstant.deviceBeanHashMap.get(address);
//                System.out.println("\tDeviceBean:" + deviceBean.getName() + " , " + address);
                    if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_TEMPERATURE) {
                        allPTDevices.add(address);
                    }
                }
            }
        }

        devices.addAll(allPTDevices);

//        devices.addAll(allPTDevices);
//        devices.addAll(allPTDevices);
//        devices.addAll(allPTDevices);
//        devices.addAll(allPTDevices);
//        devices.addAll(allPTDevices);
//        devices.addAll(allPTDevices);
//        devices.addAll(allPTDevices);
//        devices.addAll(allPTDevices);
    }

    @Override
    public int getCount() {
        return devices.size();
    }

    @Override
    public Object getItem(int position) {
        return devices.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        String address = devices.get(position);

        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.fullscreen_device_layout, null);

            holder.placeTitle = (TextView) convertView.findViewById(R.id.place_title);
            holder.deviceIcon = (ImageView) convertView.findViewById(R.id.device_icon);
            holder.deviceName = (TextView) convertView.findViewById(R.id.device_name);
            holder.deviceStatus = (TextView) convertView.findViewById(R.id.device_status);
            holder.range1 = (TextView) convertView.findViewById(R.id.range1);

            holder.deviceIcon2 = (ImageView) convertView.findViewById(R.id.device_icon2);
            holder.deviceName2 = (TextView) convertView.findViewById(R.id.device_name2);
            holder.deviceStatus2 = (TextView) convertView.findViewById(R.id.device_status2);
            holder.range2 = (TextView) convertView.findViewById(R.id.range2);

            convertView.setTag(holder);
            AutoUtils.autoSize(convertView);

        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.alarmType = 0;
        holder.alarmType2 = 0;

        {
            DeviceBean temperatureBean = SystemConstant.deviceBeanHashMap.get(address);
            AquariumBean aquariumBean = AquariumBean.findAquariumById(temperatureBean.getPlace());
            holder.placeTitle.setText(aquariumBean.getTitle());

            int functype = temperatureBean.getFunctype();
            //Temperature Icon
            if (temperatureBean.isDeepAlarm()) {
                holder.deviceIcon.setImageResource(R.drawable.deep_alarm_icon);
            } else if (temperatureBean.isAlarm()) {
                holder.deviceIcon.setImageResource(R.drawable.alarm_icon);
            } else {
                int resId = AQApplication.getChannelDrawableRes(mContext, functype);
                holder.deviceIcon.setImageResource(resId);
            }

            holder.deviceName.setText(temperatureBean.getName());

            if (functype == DeviceConstant.FUNCTYPE_TEMPERATURE) {
                double value = temperatureBean.getSensorvalue();
                int sensorUnit = temperatureBean.getSensorunit();

                if (temperatureBean.isSensorValueIsSet()) {
                    if (temperatureBean.getSensorvalue() == 0.0) {
                        holder.deviceStatus.setText(R.string.status_device_no_report);
                        holder.deviceIcon.setImageResource(R.drawable.alarm_icon);
                        holder.alarmType = 7; //device no report
                    } else {
                        holder.deviceStatus.setText(DeviceConstant.caculateValue(1, value));
                        holder.alarmType = 0; //no alarm
                    }
                } else {
                    holder.deviceStatus.setText(R.string.status_device_no_report);
                    holder.deviceIcon.setImageResource(R.drawable.alarm_icon);
                    holder.alarmType = 7; //device no report
                }

//            StringBuilder sb = new StringBuilder();
                if (DeviceConstant.alarmConditionBeanHashMap != null) {
                    AlarmConditionBean alarmConditionBean = DeviceConstant.alarmConditionBeanHashMap.get(temperatureBean.getAddress());
                    if (alarmConditionBean != null) {
//                    sb.append(alarmConditionBean.getAboveValue() + "~" + alarmConditionBean.getBelowValue());
//                    System.out.println("values:" + temperatureBean.getSensorvalue() + ", " + alarmConditionBean.getBelowValue() + ", " + alarmConditionBean.getAboveValue());
                        if (temperatureBean.getSensorvalue() > alarmConditionBean.getBelowValue()) {
                            holder.alarmType = 6; //high temperature
                        } else if (temperatureBean.getSensorvalue() < alarmConditionBean.getAboveValue()) {
                            holder.alarmType = 5; //low temperature
                        }

                        String rangeText = alarmConditionBean.getAboveValue() / 10 + "℃~" + alarmConditionBean.getBelowValue() / 10 + "℃";
                        holder.range1.setText(rangeText);
                    } else {
                        holder.range1.setText("");
                    }
                }
            }

        }

        {
            DeviceBean temperatureBean = SystemConstant.deviceBeanHashMap.get(address);
            String phAddress = "zwave://" + temperatureBean.getHomeid() + "/" + temperatureBean.getNodeid() + "/" + temperatureBean.getCommandid() + "/0/2";
            DeviceBean phBean = SystemConstant.deviceBeanHashMap.get(phAddress);
            AquariumBean aquariumBean = AquariumBean.findAquariumById(phBean.getPlace());
            holder.placeTitle.setText(aquariumBean.getTitle());

            int functype = phBean.getFunctype();
            //Temperature Icon
            if (phBean.isDeepAlarm()) {
                holder.deviceIcon2.setImageResource(R.drawable.deep_alarm_icon);
            } else if (phBean.isAlarm()) {
                holder.deviceIcon2.setImageResource(R.drawable.alarm_icon);
            } else {
                int resId = AQApplication.getChannelDrawableRes(mContext, functype);
                holder.deviceIcon2.setImageResource(resId);
            }

            holder.deviceName2.setText(phBean.getName());

            if (functype == DeviceConstant.FUNCTYPE_PH) {
                double value = phBean.getSensorvalue();
                int sensorUnit = phBean.getSensorunit();

                if (phBean.isSensorValueIsSet()) {
                    if (phBean.getSensorvalue() == 0.0) {
                        holder.deviceStatus2.setText(R.string.status_device_no_report);
                        holder.deviceIcon2.setImageResource(R.drawable.alarm_icon);
                        holder.alarmType2 = 7; //device no report
                    } else {
                        holder.deviceStatus2.setText(DeviceConstant.caculateValue(sensorUnit, value));
                        holder.alarmType2 = 0; //no alarm
                    }
                } else {
                    holder.deviceStatus2.setText(R.string.status_device_no_report);
                    holder.deviceIcon2.setImageResource(R.drawable.alarm_icon);
                    holder.alarmType2 = 7; //device no report
                }

                if (DeviceConstant.alarmConditionBeanHashMap != null) {
                    AlarmConditionBean alarmConditionBean = DeviceConstant.alarmConditionBeanHashMap.get(phBean.getAddress());
                    if (alarmConditionBean != null) {
                        if (phBean.getSensorvalue() > alarmConditionBean.getBelowValue()) {
                            holder.alarmType2 = 4; //high ph
                        } else if (phBean.getSensorvalue() < alarmConditionBean.getAboveValue()) {
                            holder.alarmType2 = 3; //low ph
                        }

                        String rangeText = alarmConditionBean.getAboveValue() + "~" + alarmConditionBean.getBelowValue();
                        holder.range2.setText(rangeText);
                    } else {
                        holder.range2.setText("");
                    }
                }
            }

        }


//        holder.deviceName.setOnClickListener(onNameClickListener);

//        if (holder.alarmType != 0) {
//            holder.deviceIcon.setOnClickListener(onAlarmIconClickListener);
//            holder.deviceIcon.setTag(R.string.alarmType, holder.alarmType);
//        } else {
//            holder.deviceIcon.setOnClickListener(onNormalIconClickListener);
//            holder.deviceIcon.setTag(R.string.alarmType, 0);
//        }

        return convertView;
    }


    @Override
    public void notifyDataSetChanged() {
        super.notifyDataSetChanged();
    }

    public void setOnNormalIconClickListener(View.OnClickListener onNormalIconClickListener) {
        this.onNormalIconClickListener = onNormalIconClickListener;
    }


    public void setOnAlarmIconClickListener(View.OnClickListener onAlarmIconClickListener) {
        this.onAlarmIconClickListener = onAlarmIconClickListener;
    }

    public void setOnNameClickListener(View.OnClickListener onNameClickListener) {
        this.onNameClickListener = onNameClickListener;
    }

    /**
     * 刷新数据
     */
    public void refreshData() {
        devices.clear();

        ArrayList<String> allPTDevices = new ArrayList<>();

        if (SystemConstant.aquariumList != null) {

            for (AquariumBean aquariumBean : SystemConstant.aquariumList) {
                ArrayList<String> deviceList = aquariumBean.getDeivices();

                for (String address : deviceList) {
                    DeviceBean deviceBean = SystemConstant.deviceBeanHashMap.get(address);
//                System.out.println("\tDeviceBean:" + deviceBean.getName() + " , " + address);
                    if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_TEMPERATURE) {
                        allPTDevices.add(address);
                    }
                }
            }
        }

        devices.addAll(allPTDevices);
//        devices.addAll(allPTDevices);
//        devices.addAll(allPTDevices);
//        devices.addAll(allPTDevices);
//        devices.addAll(allPTDevices);
//        devices.addAll(allPTDevices);
//        devices.addAll(allPTDevices);
//        devices.addAll(allPTDevices);
//        devices.addAll(allPTDevices);

        this.notifyDataSetChanged();
    }

    /**
     * 设置控制监听器
     *
     * @param onControlClickListener
     */
    public void setOnControlClickListener(View.OnClickListener onControlClickListener) {
        this.onControlClickListener = onControlClickListener;
    }

    public void setOnValueClickListener(View.OnClickListener onValueClickListener) {
        this.onValueClickListener = onValueClickListener;
    }

    static class ViewHolder {
        TextView placeTitle;
        ImageView deviceIcon;
        TextView deviceName;
        TextView deviceStatus;
        TextView range1;

        ImageView deviceIcon2;
        TextView deviceName2;
        TextView deviceStatus2;
        TextView range2;

        int alarmType; //0->no alarm, 1->low water alarm, 2->high water alarm, 3->low ph alarm, 4->high ph alarm, 5->low temperature alarm, 6->high tempearture alarm, 7->device no report, 8->low watt
        int alarmType2;
    }

}
